# !/usr/usuari/des python
#  -*- coding: utf-8 -*-
"""
@Author        : itgnay
@Time          : 2022/12/20 0:44
@FileName      : 二分查找算法.py
@LastEditors   : None
@Editors       : PyCharm
"""

arr = [10, 14, 19, 26, 27, 31, 33, 35, 42, 44]
num = 10


def binary_search(arr, num):
    may = 1  # 升序为1，降序为-1
    left = 0
    right = len(arr) - 1
    if arr[left] == num:
        return left
    elif arr[right] == num:
        return right
    elif num > arr[right] or num < arr[left]:
        return -1
    while 1:
        middle = int((left + right) / 2)
        if arr[middle] == num:
            return middle
        elif (arr[middle] - num) * may < 0:
            left = middle
        elif (arr[middle] - num) * may > 0:
            right = middle
        if right - left == 1:
            return -1


result = binary_search(arr, num)
if result == -1:
    print("该数组内找不到 %d" % num)
else:
    print("%d 在数组中的位置为 %d" % (num, result))
